#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"

cmd-tags-deploy() {
  declare desc="deploys an app with a given tagged image via command line"
  declare cmd="tags:deploy"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1" IMAGE_TAG="$2"

  [[ -z "$APP" ]] && dokku_log_fail "Please specify an app to run the command on"
  verify_app_name "$APP"

  local IMAGE="$(get_app_image_name "$APP" "$IMAGE_TAG")"
  verify_image "$IMAGE" || return 1
  release_and_deploy "$APP" "$IMAGE_TAG"

  if [[ "$IMAGE_TAG" != "latest" ]]; then
    local DOKKU_SCHEDULER="$(get_app_scheduler "$APP")"
    local LATEST_IMAGE="$(get_app_image_name "$APP")"
    plugn trigger scheduler-tags-create "$DOKKU_SCHEDULER" "$APP" "$IMAGE" "$LATEST_IMAGE"
  fi
}

cmd-tags-deploy "$@"
